package com.fagejiang.nebula.client;

import com.vesoft.nebula.Row;
import com.vesoft.nebula.Value;
import com.vesoft.nebula.client.graph.NebulaPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import com.vesoft.nebula.client.graph.data.ResultSet;
import com.vesoft.nebula.client.graph.data.ValueWrapper;
import com.vesoft.nebula.client.graph.exception.AuthFailedException;
import com.vesoft.nebula.client.graph.exception.IOErrorException;
import com.vesoft.nebula.client.graph.exception.NotValidConnectionException;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;

import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * TODO
 *
 * @author 发哥讲Java
 * @version 1.0
 * @date 2021-03-23 16:31
 */
public class TestFirst {
    public static void main(String[] args) throws NotValidConnectionException, IOErrorException, AuthFailedException, UnknownHostException, UnsupportedEncodingException {
        NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
        nebulaPoolConfig.setMaxConnSize(10);
        List<HostAddress> addresses = Collections.singletonList(new HostAddress("192.168.0.102", 9669));
        NebulaPool pool = new NebulaPool();
        pool.init(addresses, nebulaPoolConfig);
        Session session = pool.getSession("root", "nebula", false);
        final ResultSet result = session.execute("SHOW HOSTS;");
        System.out.println("result.getColumnNames() = " + result.getColumnNames());
        List<ShowHostModel> list = new ArrayList<>(5);
        for (int i = 0; i < result.rowsSize(); i++) {
            final List<ValueWrapper> values = result.rowValues(i).values();
            ShowHostModel model = new ShowHostModel();
            model.setHost(getObjectData(values.get(0)))
                    .setPort(getObjectData(values.get(1)))
                    .setStatus(getObjectData(values.get(2)))
                    .setLeaderCount(getObjectData(values.get(3)))
                    .setLeaderDistribution(getObjectData(values.get(4)))
                    .setPartitionDistribution(getObjectData(values.get(5)));
            list.add(model);
        }
        list.forEach(System.out::println);
        session.release();
        pool.close();
    }

    public static String getObjectData(ValueWrapper wrapper) throws UnsupportedEncodingException {
        if (wrapper.isString()) {
            return wrapper.asString();
        }
        if (wrapper.isLong()) {
            return String.valueOf(wrapper.asLong());
        }
        if (wrapper.isNull()) {
            return null;
        }
        if (wrapper.getValue().getSetField() == 0) {
            return null;
        }
        return wrapper.asString();
    }


}
